/**
 * 
 */
package hu.gbalage.owlforms.impl.data;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import hu.gbalage.owlforms.api.ComplexField;
import hu.gbalage.owlforms.api.Field;
import hu.gbalage.owlforms.api.Form;
import hu.gbalage.owlforms.api.data.FieldData;
import hu.gbalage.owlforms.api.data.FieldValue;
import hu.gbalage.owlforms.api.data.FormData;

/**
 * @author balage
 *
 */
public class FieldDataImpl implements FieldData {

	private final Field field;
	
	private final FormData data;

	private final List<FieldValue> values = new ArrayList<FieldValue>();
	
	public FieldDataImpl(FormData parentdata, Field field){
		data = parentdata;
		this.field = field;
	}
	
	/* (non-Javadoc)
	 * @see hu.gbalage.owlforms.api.data.FieldData#getField()
	 */
	public Field getField() {
		return field;
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.owlforms.api.data.FieldData#getFormData()
	 */
	public FormData getFormData() {
		return data;
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.owlforms.api.data.FieldData#insertValue(java.net.URI)
	 */
	public FieldValue insertValue(URI type) {
		if (field.isComplex()){
			ComplexField cf = field.asComplexField();
			Form[] forms = cf.getContainedForm();
			for(Form form : forms)
				if (form.getURI().equals(type)){
					CompositeValueImpl value = new CompositeValueImpl(new FormDataImpl(form,getFormData()));
					values.add(value);
					return value;
				}
			return null;
		}
		PrimitiveValueImpl value = new PrimitiveValueImpl(type);
		values.add(value);
		return value;
	}

	public void insertCompositeValue(FormData data) {
		if (field.isComplex())
			insertValue(new CompositeValueImpl(data));
	}
	
	/* (non-Javadoc)
	 * @see hu.gbalage.owlforms.api.data.FieldData#listValues()
	 */
	public List<FieldValue> listValues() {
		return values;
	}

	public void insertValue(FieldValue value) {
		if (field.isComplex()){
			if (!value.isPrimitive()) values.add(value);
		}else{
			if (value.isPrimitive()) values.add(value);
		}
	}
	
}
